package com.york.jobmew.circle.server.config.context;

import com.york.jobmew.circle.server.entity.constants.LoginConstant;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 登录上下文对象
 */
public class LoginContextHolder {

    private static final InheritableThreadLocal<Map<String, Object>> THREAD_LOCAL
            = new InheritableThreadLocal<>();

    /**
     * 给当前线程设置val
     *
     * @param key
     * @param val
     */
    public static void set(String key, Object val) {
        Map<String, Object> map = getThreadLocalMap();
        map.put(key, val);
    }

    /**
     * 获取当前线程的val
     *
     * @param key
     * @return
     */
    public static Object get(String key) {
        Map<String, Object> threadLocalMap = getThreadLocalMap();
        return threadLocalMap.get(key);
    }

    /**
     * 封装获取登录用户的id
     *
     * @return
     */
    public static String getLoginId() {
        return (String) getThreadLocalMap().get(LoginConstant.LOGIN_ID);
    }

    /**
     * 防止内存泄露，以及线程复用情况上下文的扰乱，每次取出来的时候都应该释放
     */
    public static void remove() {
        THREAD_LOCAL.remove();
    }

    /**
     * 实际的ThreadLocal获取方法封装
     *
     * @return
     */
    public static Map<String, Object> getThreadLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (Objects.isNull(map)) {
            map = new ConcurrentHashMap<>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }

}
